package com.zzyl.framework.interceptor.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.core.domain.AjaxResult;

import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是Controller层的请求，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //获取token
        String token = request.getHeader("authorization");
        if(StrUtil.isBlank(token)){
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            AjaxResult ajaxResult = AjaxResult.error(401, "没有token");
            response.getWriter().write(JSONUtil.toJsonStr(ajaxResult));
            return false;
        }
        try {
            //解析token
            Claims claims = tokenService.parseToken(token);
            Long userId = claims.get("userId", Long.class);
            if(userId == null){
                response.setStatus(401);
                response.setContentType("application/json;charset=UTF-8");
                AjaxResult ajaxResult = AjaxResult.error(401, "token解析后没有载荷");
                response.getWriter().write(JSONUtil.toJsonStr(ajaxResult));
                return false;
            }
            //将信息放到ThreadLocal中
            UserThreadLocal.set(userId);
            //放行
            return true;
        } catch (Exception e) {
            log.error("解析token失败，出现异常:",e);
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            AjaxResult ajaxResult = AjaxResult.error(401, "token解析失败");
            response.getWriter().write(JSONUtil.toJsonStr(ajaxResult));
            return false;
        }



    }

    //方法放行之后，清理UserThreadLocal
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
